const loginDao = require('../dao/loginDao');

const axios = require('axios');
const { createUserJwtToken, verifyJwtToken } = require('../util/server_jwt');

const total_config = require('../config');
const { appid, secret } = total_config.wx;

const loginService = {
    async wxLogin(code) {
        // 向微信服务器发请求获取用户信息
        let data;
        try {
            const response = await axios.get(`https://api.weixin.qq.com/sns/jscode2session`, {
                params: {
                    appid: appid,
                    secret: secret,
                    js_code: code,
                    grant_type: 'authorization_code'
                }
            });
            data = response.data;
            if (data.errcode) {
                return { code: 500, msg: '获取用户信息失败' };
            }
        } catch (error) {
            console.log(error);
            return { code: 500, msg: '获取用户信息失败' };
        }
        // 获取openid
        let openid = data.openid;
        // 验证登录
        let result;
        let uid;
        let isNewUser;
        try {
            // 尝试查询是否有用户在数据库里
            let tmp = await loginDao.loginByOpenid(openid);
            if (tmp.length == 0) {
                tmp = await loginDao.addUser(openid);
                uid = tmp.insertId;
                isNewUser = true;
            } else {
                uid = tmp[0].id;
                isNewUser = JSON.parse(tmp[0].isNewUser);
            }

            // 生成jwt令牌
            let payload = { uid };
            // 将 jwt令牌 的有效时间设置为 20小时
            let jwt = await createUserJwtToken(payload, { expiresIn: '20h' });
            
            // 返回数据
            result = { code: 200, msg: "登录成功", data: { token: jwt, isNewUser: isNewUser } };
        } catch (err) {
            result = { code: 500, msg: "数据库异常", data: null };
        }
        return result;
    },
    async checkUserToken(token) {
        return verifyJwtToken(token);
    }
};

module.exports = loginService;